import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:ichinesereader/exam/dto/assessment.response.dart';
import 'package:ichinesereader/exam/dto/assessment_question_record.body.dart';
import 'package:ichinesereader/exam/widgets/BGSinglePlayer.dart';
import 'package:ichinesereader/service/assessment.dart';
import 'package:ichinesereader/utils/log.dart';

class BGQuizController extends GetxController {
  final AssessmentServiceProvider _service = AssessmentServiceProvider();
  AssessmentResult? assessmentResult;
  RxBool isLoad = false.obs;
  ScrollController scrollCrl = ScrollController();
  String assessmentId = '';
  String username = '';
  List<List<GlobalKey>> keyList = [];
  List<List<String>> indexList = [];
  List allItems = [];
  List allSectionContent = [];
  RxInt currentIndex = (-1).obs;
  RxInt currentSection = (-1).obs;
  Map<int, Map<int, int>> sectionIndexMap = {};
  Map<int, int> indexAndSectionMap = {};

  void nextPage() {
    currentIndex++;
    getCurrentSection();
  }

  void prevPage() {
    currentIndex--;
    getCurrentSection();
  }

  void getCurrentSection() {
    currentSection.value = indexAndSectionMap[currentIndex.value]!;
  }

  Future<void> loadData(String assessmentId) async {
    EasyLoading.show();
    try {
      var result = await _service.getAssessment(assessmentId);
      assessmentResult = result;
      int totalNum = 0;
      for (int i = 0; i < assessmentResult!.list!.length; i++) {
        QuestionPart? part = assessmentResult!.list?[i];
        for (int j = 0; j < part!.questions!.length; j++) {
          QuestionSection section = part.questions![j];
          int sectionNum = j;
          String sectionNumStr = (sectionNum + 1).toString() + '.';
          List<String> tempIndexList = [];
          List<GlobalKey> tempKeyList = [];
          Map<int, int> tempIndexNumMap = {};
          allSectionContent.add(section.content);
          for (int k = 0; k < section.question!.length; k++) {
            tempIndexNumMap[k] = totalNum;
            indexAndSectionMap[totalNum] = sectionNum;
            totalNum++;
            QuestionItem item = section.question![k];
            allItems.add(item);
            item.head!.questionTitleNum = sectionNumStr + ' ';
            if (section.question!.length > 1) {
              item.head!.questionTitleNum = sectionNumStr + (k + 1).toString() + ' ';
            }
            tempIndexList.add(item.head!.questionTitleNum!);
            var key = GlobalKey();
            tempKeyList.add(key);
          }
          indexList.add(tempIndexList);
          keyList.add(tempKeyList);
          sectionIndexMap[sectionNum] = tempIndexNumMap;
        }
      }
      isLoad.value = true;
      currentIndex.value = 0;
      getCurrentSection();
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<void> scrollToIndex(int section, int index) async {
    Future.delayed(Duration.zero).then((value) async {
      WidgetsBinding.instance.addPostFrameCallback(
          (_) => Scrollable.ensureVisible(keyList[section][index].currentContext!, duration: Duration(milliseconds: 500), alignment: 0.1));
    });
  }

  Future<void> reportRecord() async {
    EasyLoading.show();
    try {
      await _service.postQuestionRecord(QuestionRecordBody(
          assessmentId: assessmentId,
          questionGroupId: assessmentResult?.questionGroupId ?? '',
          userName: username,
          progressStatus: "{\"pageIndex\":1}",
          record: _buildQuestionRecordList()));
    } catch (e) {
      Log.debug(e);
    } finally {
      EasyLoading.dismiss();
    }
  }

  Future<void> submitAction() async {
    BGSinglePlayer().stop();
    EasyLoading.show();
    try {
      _service.postSubmitReportRecord(QuestionRecordBody(
          assessmentId: assessmentId,
          questionGroupId: assessmentResult?.questionGroupId ?? '',
          userName: username,
          progressStatus: "{\"pageIndex\":1}",
          record: _buildQuestionRecordList()));
    } catch (e) {
      Log.debug(e);
    } finally {
      Future.delayed(const Duration(milliseconds: 500), () {
        EasyLoading.dismiss();
        Get.back();
      });
    }
  }

  List verifyCompleteAllQuestion() {
    AssessmentResult? result = assessmentResult;
    var partDataList = result!.list;
    List<String> questionNumList = [];
    //Part
    for (var pIndex = 0; pIndex < partDataList!.length; pIndex++) {
      var partData = partDataList[pIndex];
      var sectionDataList = partData.questions;
      //Section
      for (var sIndex = 0; sIndex < sectionDataList!.length; sIndex++) {
        var sectionData = sectionDataList[sIndex];
        var questionDataList = sectionData.question;
        //Question
        for (var qIndex = 0; qIndex < questionDataList!.length; qIndex++) {
          QuestionItem questionData = questionDataList[qIndex];
          int sectionNum = 0;
          if (pIndex > 0) {
            sectionNum = pIndex;
          } else {
            if (sIndex > 0) sectionNum = sIndex;
          }
          String questionTitleNum = (sectionNum + 1).toString();
          if (questionDataList.length > 1) questionTitleNum += '.' + (qIndex + 1).toString();

          if (questionData.answer == null || questionData.answer!.isEmpty) {
            questionNumList.add(questionTitleNum);
          } else {
            if (questionData.type != 'match' &&
                questionData.answerCount != null &&
                questionData.answerCount! > 1 &&
                questionData.answer!.length < questionData.answerCount!) {
              questionNumList.add(questionTitleNum);
            }
          }
        }
      }
    }
    return questionNumList;
  }

  List<Map> _buildQuestionRecordList() {
    List<Map> questionRecordList = [];
    AssessmentResult? result = assessmentResult;
    var partDataList = result!.list;
    for (var pIndex = 0; pIndex < partDataList!.length; pIndex++) {
      var partData = partDataList[pIndex];
      var sectionDataList = partData.questions;
      //Section
      for (var sIndex = 0; sIndex < sectionDataList!.length; sIndex++) {
        var sectionData = sectionDataList[sIndex];
        var questionDataList = sectionData.question;
        //Question
        for (var qIndex = 0; qIndex < questionDataList!.length; qIndex++) {
          QuestionItem questionData = questionDataList[qIndex];
          questionRecordList.add(QuestionSingleStep(answer: questionData.answer, number: questionData.number, questionId: sectionData.id).toJson());
        }
      }
    }
    return questionRecordList;
  }

  @override
  Future<void> onClose() async {
    BGSinglePlayer().stop();
    scrollCrl.dispose();
    await reportRecord();
    _service.dispose();
    super.onClose();
  }
}
